import { Application } from 'egg';
import { Anexcuse } from '../model/Anexcuse';

export default (app: Application) => {
    return {
        schedule: {
            interval: app.config.cacheTick,
            type: 'all',
        },
        async task() {
            const resultAnexcuse: any = await app.model.Anexcuse.findAll<Anexcuse>({
                attributes: ['anexcuse_id', 'user_id', 'anexcuse_time'],
                where: { is_delete: '1' }
            });
            for (let i = 0; i < resultAnexcuse.length; i++) {
                let newAnexcuseTime = resultAnexcuse[i].anexcuse_time - 5;
                if (newAnexcuseTime <= 0) {
                    const tran = await app.model.transaction();
                    try {
                        await app.model.Anexcuse.update({ anexcuse_time: 0, is_delete: '2' }, { where: { anexcuse_id: resultAnexcuse[i].anexcuse_id } });
                        await app.model.User.update({ user_status: '3' }, { where: { user_id: resultAnexcuse[i].user_id } });
                        await app.model.Accusation.update({ accusation_status: '1' }, { where: { report_user_id: resultAnexcuse[i].user_id,accusation_status:'4' } });
                        await tran.commit();
                    } catch (e) {
                        await tran.rollback();
                        app.logger.error(e);
                    }
                } else {
                    await app.model.Anexcuse.update({ anexcuse_time: newAnexcuseTime }, { where: { anexcuse_id: resultAnexcuse[i].anexcuse_id } });
                }
            }
        },
    };
};
